package com.wltt.healing.healingusercommon.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.LongSerializationPolicy;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @Author: wltt
 * @Date: 2021/10/7 17:56：
 * @Version: 1.0
 * @Description: TODO
 */
public abstract class JsonUtil {

    private static ObjectMapper mapper = new ObjectMapper()
            .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    private static final Gson GSON = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .setLongSerializationPolicy(LongSerializationPolicy.STRING)
            .disableHtmlEscaping()
            .create();

    /**
     * 对象转json
     *
     * @param object 对象
     * @return the string
     */
    public static String toJson(Object object) throws JsonProcessingException {
        return mapper.writeValueAsString(object);
    }

    /**
     * json转对象
     *
     * @param json json字符串
     * @param tClass 类型
     * @return the string
     */
    public static <T> T toObject(String json, Class<T> tClass) {
        return GSON.fromJson(json, tClass);
    }

    /**
     * json转对象
     * 用于json转map，Gson在转map的时候，对Long类型处理容易丢失精度
     *
     * @param jsonStr json字符串
     * @return the string
     */
    public static Map toMap(String jsonStr) throws IOException {
        return mapper.readValue(jsonStr, Map.class);
    }
}
